<template>
  <div class="branchIncludeService">
    <my-tree-selector-query
      title="选择网点"
      :options="branchDataOptions"
      :treeProps="{ children: 'children',label: 'branchName'}"
      @click-node="handleNodeClick"
      node-key="branchCode"
      :default-expanded-keys="[0]"
      :current-node-key="queryParams.branchCode"
    />

    <div class="right-wrap">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="事项名称" prop="serviceName">
          <el-input
            v-model="queryParams.serviceName"
            placeholder="请输入事项名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="事项编码" prop="serviceCode">
          <el-input
            v-model="queryParams.serviceCode"
            placeholder="请输入事项编码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="事项类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择事项类型">
            <el-option
              v-for="item in navTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-connection"
            size="mini"
            @click="handleAssociateService"
            v-hasPermi="['items:service:addServiceBranchRelation']"
            :disabled="queryParams.branchCode === undefined"
          >关联网点事项
          </el-button>
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleDeleteAssociate()"
            v-hasPermi="['items:service:deleteServiceBranchRelation']"
            :disabled="checkedServiceCodes.length === 0"
          >删除关联
          </el-button>
        </el-col>
        <el-col :span="1.5" style="float: right">
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <el-button size="mini" circle icon="el-icon-refresh" @click="getIncludedAffairList"/>
          </el-tooltip>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="includedServiceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="事项编码" width="190" align="center" prop="serviceCode"/>
        <el-table-column label="事项名称" align="center" prop="serviceName"/>
        <el-table-column label="事项类型" align="center" prop="type">
          <template slot-scope="props">
            {{ serviceTypeLabel(props.row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="事项路由地址" align="center" prop="serviceUrl"/>
        <el-table-column label="是否启用" align="center">
          <template slot-scope="props">
            {{ props.row.enable === 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteAssociate(scope.row)"
              v-hasPermi="['items:service:remove']"
            >删除关联
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getIncludedAffairList"
      />
    </div>


    <!-- 关联事项 -->
    <el-dialog
      :visible.sync="openAssociateServiceDialog"
      width="1200px"
      :title="associateServiceDialogTitle"
      append-to-body
      :close-on-click-modal="false"
      @close="closeAssociateServiceDialogCallback"
    >
      <template>
        <div v-loading="associateServiceDialogLoading">

          <div style="margin-bottom: 20px">
            <el-input
              v-model="associateServiceQueryParams.serviceName"
              placeholder="请输入事项名称"
              clearable
              size="small"
              @keyup.enter.native="handleAssociateServiceSearch"
              style="width: 300px; margin-right: 10px"
            />
            <el-input
              v-model="associateServiceQueryParams.deptName"
              placeholder="请输入部门名称"
              clearable
              size="small"
              @keyup.enter.native="handleAssociateServiceSearch"
              style="width: 300px; margin-right: 10px"
            />
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleAssociateServiceSearch">搜索
            </el-button>
          </div>

          <el-table
            ref="associateServiceTable"
            max-height="500px"
            :data="associateServiceList"
            @selection-change="handleAssociateServiceSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="事项编码" width="190" align="center" prop="serviceCode"/>
            <el-table-column label="事项名称" align="center" prop="serviceName"/>
            <el-table-column label="事项类型" align="center" width="180" prop="type">
              <template slot-scope="props">
                {{ serviceTypeLabel(props.row.type) }}
              </template>
            </el-table-column>
            <el-table-column label="是否启用" align="center" width="120">
              <template slot-scope="props">
                {{ props.row.enable === 1 ? "是" : "否" }}
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="associateServiceListTotal>0"
            :total="associateServiceListTotal"
            layout="total, prev, pager, next, jumper"
            :page.sync="associateServiceQueryParams.pageNum"
            :limit.sync="associateServiceQueryParams.pageSize"
            @pagination="handlePageChange"
          />
        </div>
      </template>

      <div slot="footer" class="dialog-footer">
        <div class="tip">
          注意：可选勾选多页多个事项一次性关联
        </div>
        <el-button
          type="primary"
          @click="handleConfirmAssociateService">
          确定关联
        </el-button>
        <el-button @click="openAssociateServiceDialog = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import MyTreeSelectorQuery from "@/views/components/myTreeSelectorQuery/index";
import {
  listServiceInBranch,
  listServiceNotInBranch,
  deleteServiceBranchRelation,
  addServiceBranchRelation
} from "@/api/items/service";
import {navTypeOptions} from '@/utils/dicts'

export default {
  name: "branchIncludeService",
  components: {MyTreeSelectorQuery},
  data() {
    return {
      // 网点包含的事项立碑
      includedServiceList: [],
      // 选中数组
      checkedServiceCodes: [],
      // 遮罩层
      loading: false,
      showSearch: true,
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        
        branchCode: undefined,
        serviceName: undefined,
        serviceCode: undefined,
        type: undefined
      },
      navTypeOptions,
      // 关联事项弹窗
      openAssociateServiceDialog: false,
      // 关联事项弹窗加载中
      associateServiceDialogLoading: false,
      // 关联弹窗获取列表参数
      associateServiceQueryParams: {
        pageNum: 1,
        pageSize: 10,
        serviceName: undefined,
        deptName:undefined,
      },
      // 关联事项弹窗里面可关联事项列表
      associateServiceList: [],
      // 已勾选中的关联事项列表缓存
      cacheSelectedAssociateServices: [],
      // 当前页面选中的关联事项
      currentPageSelectedList: [],
      // 关联网点事项列表总数
      associateServiceListTotal: 0,
      // 当前选中的网点名称
      currentSelectedBranchName: ''
    }
  },
  computed: {
    branchDataOptions() {
      return this.$store.state.device.branchDataOptions || [];
    },
    associateServiceDialogTitle() {
      return `关联网点事项 【${this.currentSelectedBranchName}】`
    }
  },
  methods: {
    resetQuery() {
      this.queryParams.serviceCode = undefined;
      this.queryParams.serviceName = undefined;
      this.queryParams.type = undefined;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getIncludedAffairList();
    },
    /** 删除按钮操作 */
    handleDeleteAssociate(row) {
      const checkedServiceCodes = row ? [row.serviceCode] : this.checkedServiceCodes;
      this.$modal.confirm('是否确认删除该关联事项？').then(() => {
        return deleteServiceBranchRelation({
          branchCode: this.queryParams.branchCode,
          serviceCodeList: checkedServiceCodes
        });
      }).then(() => {
        this.getIncludedAffairList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {

      });
    },

    // 关联网点事项弹窗分页页数改变
    handlePageChange() {
      // 缓存已选中事项信息
      this.saveSelectedItemToCacheList();
      this.getCanAssociateServiceList();
    },

    // 将选中项推入缓存列表，未选中的从缓存列表删除
    saveSelectedItemToCacheList(needClearCurrentPage = true) {
      // 当前页所有事项serviceCode
      const currentPageIds = this.associateServiceList.map(item => item.serviceCode);

      // 将当前页数据从缓存中删除，再在将已选中的加入到缓存
      this.cacheSelectedAssociateServices = this.cacheSelectedAssociateServices.filter(item => {
        return !currentPageIds.includes(item.serviceCode)
      }).concat(this.currentPageSelectedList);

      // console.log("缓存的列表", this.cacheSelectedAssociateServices)

      // 清空当前页的选中数据
      if(needClearCurrentPage) this.currentPageSelectedList = [];
    },

    // 确定关联事项
    handleConfirmAssociateService() {
      // 将当前选中项保存到缓存选中列表
      this.saveSelectedItemToCacheList(false);
      if (!this.cacheSelectedAssociateServices.length) {
        return this.$alert(
          `请勾选要关联的事项！`,
          '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          });
      }

      this.$confirm(`是否确定将已选中的${this.cacheSelectedAssociateServices.length}个事项关联到【${this.currentSelectedBranchName}】网点？`,
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        addServiceBranchRelation({
          branchCode: this.queryParams.branchCode,
          serviceList: this.cacheSelectedAssociateServices
        }).then(response => {
          this.$modal.msgSuccess("新增关联成功");
          this.openAssociateServiceDialog = false;
          // 清空缓存当前页选中的数据
          this.currentPageSelectedList = [];
          // 重新获取
          this.getIncludedAffairList();
        });
      }).catch(() => {
      });

    },

    // 关联事项弹窗多选框选择改变
    handleAssociateServiceSelectionChange(selection) {
      // 当前页选中列表
      this.currentPageSelectedList = selection;
    },

    // 关联事项弹窗搜索按钮
    handleAssociateServiceSearch() {
      // 缓存已选中事项信息
      this.saveSelectedItemToCacheList();
      this.getCanAssociateServiceList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.checkedServiceCodes = selection.map(item => item.serviceCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 关联网点事项
    handleAssociateService() {
      this.openAssociateServiceDialog = true;
      this.associateServiceQueryParams.serviceName = undefined
      this.associateServiceQueryParams.deptName=undefined
      // 重置为第一页
      this.associateServiceQueryParams.pageNum = 1;
      this.getCanAssociateServiceList();
    },
    // 关闭关联事项弹窗回调
    closeAssociateServiceDialogCallback() {
      // 关闭弹窗后清空选中缓存列表和选中列表
      this.cacheSelectedAssociateServices = [];
      this.currentPageSelectedList = [];
      this.associateServiceList = [];
    },
    // 获取可关联事项列表
    getCanAssociateServiceList() {
      // 显示加载中
      this.associateServiceDialogLoading = true;

      // 调用接口获取可添加的事项数据
      listServiceNotInBranch({
        ...this.associateServiceQueryParams,
        branchCode: this.queryParams.branchCode
      }).then(response => {
        this.associateServiceDialogLoading = false;
        this.associateServiceList = response.rows.map(item => {
          // 判断是否存在缓存里面，如果存在使用缓存里面的数据进行回填信息
          const cacheItem = this.cacheSelectedAssociateServices.find(cacheItem => {
            return cacheItem.serviceCode === item.serviceCode
          })
          if (cacheItem) return cacheItem;
          return {
            ...item,
            icon: '',
            serviceUrl: '',
            // type: 3,
            enable: 1,
          }
        });
        this.associateServiceListTotal = response.total;
        // 设置表格多选框默认选中
        this.$nextTick(() => {
          for (let i = 0; i < this.associateServiceList.length; i++) {
            const row = this.associateServiceList[i];
            if (this.cacheSelectedAssociateServices.some(item => row.serviceCode === item.serviceCode)) {
              this.$refs.associateServiceTable.toggleRowSelection(row);
            }
          }
        })
      });
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.branchCode = data.branchCode;
      this.currentSelectedBranchName = data.branchName;
      this.handleQuery()
    },
    /** 查询事项列表 */
    getIncludedAffairList() {
      if (!this.queryParams.branchCode) return this.$modal.msgWarning('请先选择网点！')
      this.loading = true;
      listServiceInBranch(this.queryParams).then(response => {
        this.includedServiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 事项类型文本
    serviceTypeLabel(value) {
      const item = navTypeOptions.find(item => {
        return item.value == value 
      })
      return item ? item.label : null
    },
  },
  watch: {
    branchDataOptions: {
      handler(val) {
        if (val.length) {
          // 默认选中第一个
          this.queryParams.branchCode = val[0].branchCode;
          this.currentSelectedBranchName = val[0].branchName;
          this.queryParams.pageNum = 1;
          this.getIncludedAffairList();
        }
      },
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
.branchIncludeService {
  display: flex;
  width: 100%;
  height: 100%;


  .right-wrap {
    flex: 1;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
}

.dialog-footer {
  position: relative;

  .tip {
    position: absolute;
    left: 0;
    top: 0;
    font-size: 16px;
    line-height: 36px;
    color: red;
  }
}
</style>
